﻿using Aspose.Html.Collections;
using Aspose.Html.Saving;
using Aspose.Slides;
using Aspose.Slides.Util;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace Test1.Controllers
{
    public class HomeController : Controller
    {
        public HomeController()
        {
            License license = new License();
            license.SetLicense(System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "License.lic"));

            Aspose.Html.License license1 = new Aspose.Html.License();
            license1.SetLicense(System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "License.lic"));


            Aspose.Pdf.License license2 = new Aspose.Pdf.License();
            license2.SetLicense(System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "License.lic"));
             
        }

        public ActionResult Index()
        {
            return View();
        }

        public ActionResult svg()
        { 
            return View();
        }

        public ActionResult svg1()
        {
            return View();
        }

        [HttpPost]
        public ActionResult ConvertPPt()
        {
            List<PPTSlideInfo> lst = new List<PPTSlideInfo>();
            string path = Server.MapPath("/upload/vue.pptx");
            string fileName = System.IO.Path.GetFileNameWithoutExtension(path);
            string webPath = Server.MapPath("/upload/" + fileName);
            if (!System.IO.Directory.Exists(webPath))
            {
                System.IO.Directory.CreateDirectory(webPath);
            }
            if (!System.IO.Directory.Exists(System.IO.Path.Combine(webPath, "thumbnail")))
            {
                System.IO.Directory.CreateDirectory(System.IO.Path.Combine(webPath, "thumbnail"));
            }
            if (!System.IO.Directory.Exists(System.IO.Path.Combine(webPath, "svg")))
            {
                System.IO.Directory.CreateDirectory(System.IO.Path.Combine(webPath, "svg"));
            }
            if (!System.IO.Directory.Exists(System.IO.Path.Combine(webPath, "md")))
            {
                System.IO.Directory.CreateDirectory(System.IO.Path.Combine(webPath, "md"));
            }
            int index = 0;
            using (Aspose.Slides.Presentation pre = new Aspose.Slides.Presentation(path))
            {
                foreach (ISlide slide in pre.Slides)
                {
                    using (Aspose.Slides.Presentation temp = new Presentation())
                    {

                        var lstHy = new List<HyperlinkInfo>();
                        ITextFrame[] textFramesSlideOne = SlideUtil.GetAllTextBoxes(slide);

                        //Loop through the Array of TextFrames
                        for (int i = 0; i < textFramesSlideOne.Length; i++)
                        {
                            int cnt = textFramesSlideOne[i].Paragraphs.Count;

                            for (int parIndex = 0; parIndex < cnt; parIndex++)
                            {
                                IParagraph para = textFramesSlideOne[i].Paragraphs[parIndex];

                                //Loop through portions in the current Paragraph
                                for (int portIndex = 0; portIndex < para.Portions.Count; portIndex++)
                                {
                                    IPortion port = para.Portions[portIndex];
                                    if (port.PortionFormat.HyperlinkClick != null)
                                    {
                                        lstHy.Add(new HyperlinkInfo { title = port.Text, url = port.PortionFormat.HyperlinkClick.ExternalUrl });
                                    }
                                }
                            }
                        }
                        //ppt的缩略图
                        var bitmap = slide.GetThumbnail(new System.Drawing.Size(400, 300));
                        string thumbnail = $"/upload/{fileName}/thumbnail/{index.ToString()}.jpg";
                        bitmap.Save(Server.MapPath(thumbnail));
                        //ppt的标题
                        string title = slide.GetTitles($"第{index}页PPT");
                        //ppt的备注 
                        string remark = slide.NotesSlideManager.NotesSlide.NotesTextFrame.Text;

                        //转出成后html
                        temp.SlideSize.SetSize(pre.SlideSize.Size.Width, pre.SlideSize.Size.Height, Aspose.Slides.SlideSizeScaleType.DoNotScale);
                        temp.SlideSize.Orientation = pre.SlideSize.Orientation;
                        temp.Slides.RemoveAt(0);
                        temp.Slides.AddClone(slide);
                        string html = $"/upload/{fileName}/{index.ToString()}.html";
                        temp.Save(Server.MapPath(html), Aspose.Slides.Export.SaveFormat.Html);

                        HtmlAgilityPack.HtmlDocument htmlDocument = new HtmlAgilityPack.HtmlDocument();
                        htmlDocument.Load(Server.MapPath(html));

                        foreach (var htmlNode in htmlDocument.DocumentNode.ChildNodes)
                        {
                            var str1 = htmlNode.InnerHtml;
                        }

                        string svgPath = $"/upload/{fileName}/svg/{index.ToString()}.svg";
                        ////1.采用html输出svg
                        //string htmlContent = "";
                        //Aspose.Html.HTMLDocument htmlDoc = new Aspose.Html.HTMLDocument(Server.MapPath(html));
                        ////移除html生成md文件             
                        ////string mdPath = $"/upload/{fileName}/md/{index.ToString()}.md";
                        ////htmlDoc.Save(Server.MapPath(mdPath), HTMLSaveFormat.Markdown);

                        //HTMLCollection svg = htmlDoc.GetElementsByTagName("svg");
                        //if (svg.Length == 1)
                        //{
                        //    var ss = svg[0];
                        //    string c = ss.InnerHTML;
                        //    htmlContent = ss.OuterHTML;
                        //}
                        //StreamWriter streamWriter = new StreamWriter(Server.MapPath(svgPath));
                        //streamWriter.Write(htmlContent);
                        //streamWriter.Close();

                        //2.采用替换的方式进行
                        

                        string content = System.IO.File.ReadAllText(Server.MapPath(html));
                   

                      //  System.Text.RegularExpressions.Regex regex = new System.Text.RegularExpressions.Regex("<svg *?</svg>");
                      // bool b= regex.IsMatch(content);
                      //string s=  regex.Match(content).Value; 
                        string ss = content.Replace("<!DOCTYPE html>","")
                            .Replace("<html>","")
                            .Replace("<head>", "")
                            .Replace("<meta http-equiv=\"X-UA-Compatible\" content=\"IE=9\" charset=\"utf-8\">", "")
                            .Replace("</head>", "")
                            .Replace("<body>", "")
                            .Replace("<div class=\"slide\" name=\"slide\" id=\"slideslideIface1\" >", "")
                            .Replace("</div></body>", "")
                            .Replace("</html>", "")
                            ;
                        StreamWriter streamWriter = new StreamWriter(Server.MapPath(svgPath));
                        streamWriter.Write(ss);
                        streamWriter.Close();

                        lst.Add(new PPTSlideInfo { index = index, title = title, remark = remark, thumbnail = thumbnail, html = html, lstHyperlinkInfo = lstHy, svg= svgPath });
                    }
                    index += 1;
                }
            }

            string str = Newtonsoft.Json.JsonConvert.SerializeObject(lst);
            using (StreamWriter writer = new StreamWriter(Server.MapPath("/Scripts/data.json")))
            {
                writer.Write(str);
            }
            return Json(new { message = "转化完成" });
        }

        [HttpPost]
        public ActionResult GetPPTResult()
        {
            System.IO.StreamReader sr = System.IO.File.OpenText(Server.MapPath("/Scripts/data.json"));
            string content = sr.ReadToEnd();
            List<PPTSlideInfo> lst = new List<PPTSlideInfo>();
            lst = Newtonsoft.Json.JsonConvert.DeserializeObject<List<PPTSlideInfo>>(content);
            return Json(lst);
        }       

        class PPTSlideInfo
        {
            public int index { get; set; }
            public string title { get; set; }
            public string remark { get; set; }
            public string thumbnail { get; set; }

            public string html { get; set; }

            public string svg { get; set; }
            
            public List<HyperlinkInfo> lstHyperlinkInfo { get; set; }

        }

        public class HyperlinkInfo
        {
            public string title { get; set; }
            public string url { get; set; }
        }


    }
}